package com.ruoyi.file.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;  
import org.springframework.web.multipart.MultipartFile;  
  
import java.io.IOException;
import java.io.InputStream;

@Component  
public class OssUtil {  
  
    @Value("${oss.endpoint}")  
    private  String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;
  
    @Value("${oss.accessKeySecret}")  
    private  String accessKeySecret;
  
    @Value("${oss.bucketName}")  
    private  String bucketName;

    @Value("${oss.furl}")
    private String furl;

    private String objectName = "upload/";

    public String upload(String fileName, InputStream in, ObjectMetadata metadata) {
        // 先重置为初始值
        objectName = "upload/";
        // 组合 objectName
        objectName = objectName + fileName;
        // 创建 OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 上传
        PutObjectResult result = ossClient.putObject(bucketName, objectName, in, metadata);
        // 关闭连接
        ossClient.shutdown();
        // 组合新名称并返回
        return furl + objectName;
    }  
}